﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

namespace TCG
{
	/// <summary>
	/// 贴图数据库，加载贴图、保存贴图信息等。
	/// </summary>

    public class GameTextureDatabase : BaseAssetsDatabase<Texture> 
	{
		public override void UnloadUnusedAssets ()
		{
			Debug.Log ("GameTextureDatabase: UnloadUnusedAssets");
			foreach (KeyValuePair<uint, int> _pair in m_zeroRefAssets)
			{
				uint assetId = _pair.Key;
				GameAsset<Texture> textureAsset = m_cachedAssets[assetId];
				Debug.Log ("* " + textureAsset.ToString ());
				Texture texture = textureAsset.asset;
				GameObject.DestroyImmediate (texture, true);
				m_cachedAssets.Remove (assetId);
			}
			m_zeroRefAssets.Clear ();
		}

        protected override string GetMapFilePath()
        {
            return CommonTools.GetStreamingPath ("Config/texture_map");
        }

        protected override void DoLoad (AssetRequest request)
        {
			m_assetLoader.LoadAssetBundle (request, LoadCallback);
        }

		void LoadCallback (AssetRequest request, AssetBundle assetBundle)
		{
			if (!string.IsNullOrEmpty (request.error))
			{
				OnLoadFail (request.assetId, request.error);
			}
			else
			{
				Texture texture = assetBundle.mainAsset as Texture;
				assetBundle.Unload (false);
				OnLoadSuccess (request.assetId, texture);
			}
		}
	}
}
